package com.ee.chat.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.admin.service.IUserService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.*;
import com.ee.chat.common.entity.*;
import com.ee.chat.common.serconfig.MyAliOSSConfig;
import com.ee.chat.common.serconfig.MyNeteaseApp;
import com.ee.chat.common.service.IPushMessageService;
import com.ee.chat.common.service.IUpdateEntityService;
import com.ee.chat.common.service.IYieldService;
import com.ee.chat.common.util.ConstantsUtil;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.PageUtil;
import com.ndhutu.ee.util.StringUtil;
import com.ndhutu.ee.util.netease.im.IMUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements IUserService {
    @Resource
    UserMapper userMapper;
    @Resource
    UserWalletMapper userWalletMapper;
    @Resource
    UserCoinLogMapper userCoinLogMapper;
    @Resource
    UserCreditLogMapper userCreditLogMapper;
    @Resource
    UserInviteLogMapper userInviteLogMapper;
    @Resource
    ChannelMapper channelMapper;
    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;
    @Resource
    ChannelUserLogMapper channelUserLogMapper;
    @Resource
    SysConfigMapper sysConfigMapper;
    @Resource
    UserSealLogMapper userSealLogMapper;
    @Resource
    IPushMessageService pushMessageService;
    @Resource
    UserImLogMapper userImLogMapper;
    @Resource
    DisableImeiMapper imeiMapper;
    @Resource
    UserImLimitLogMapper userImLimitLogMapper;
    @Resource
    PayChannelConfigMapper payChannelConfigMapper;
    @Resource
    UserSetMapper userSetMapper;
    @Resource
    UserOnlineLogMapper userOnlineLogMapper;
    @Resource
    SysOrderMapper sysOrderMapper;
    @Resource
    UserWithdrawLogMapper userWithdrawLogMapper;

    @Resource
    MyNeteaseApp app;
    @Resource
    MyAliOSSConfig aliOSSConfig;

    @Resource
    IOperationService operationService;
    @Resource
    IYieldService yieldService;
    @Resource
    IUpdateEntityService updateEntityService;

    @Override
    public Result list(HttpServletRequest request, Integer page, Integer limit, String keyword, Integer status,
                       Integer host, Integer gender, Integer identity, String createTime, String field, String sort) throws Exception {

        Map<String, Object> data = new HashMap<>();
        if(status == null && host == null && gender == null && identity == null
                && StringUtil.isEmpty(keyword) && StringUtil.isEmpty(createTime)){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/user/viewList")){
                data.put("users", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(createTime)){
            String[] arr = createTime.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }

        List<Map<String, Object>> users = userMapper.list(keyword, status, host, gender,
                identity, beginTime, endTime, field, sort, PageUtil.getOffset(page, limit), limit);
        for(Map<String, Object> user : users) {
            DisableImei imei = imeiMapper.getDisableImei(user.get("imei") + "");
            user.put("imeiReason", imei == null ? null : imei.getReason());
        }

        data.put("users", users);
        data.put("total", userMapper.listCount(keyword, status, host, gender, identity, beginTime, endTime));

        operationService.addOperationLog(request, "获取用户数据列表");

        return Result.returnSuccess(data);
    }

    @Override
    public Result toEdit(HttpServletRequest request, Integer id) throws Exception {
        Map<String, Object> data = new HashMap<>();

        User user = userMapper.selectById(id);
        data.put("user", user);

        return Result.returnSuccess(data);
    }

    @Override
    public Result edit(HttpServletRequest request, User user) throws Exception {
        userMapper.updateById(user);

        //更新IM信息
        String ossUrl = "https://"+aliOSSConfig.getBucketName()+"."+aliOSSConfig.getEndpoint()+"/";
        IMUtil.updateUinfo(app.getIdPrefix()+user.getId(), user.getName(), ossUrl+user.getIcon(), user.getGender(), app);

        operationService.addOperationLog(request, "更新"+user.getId()+"用户基本信息");

        return Result.returnSuccess(null);
    }

    @Override
    public Result updateStatus(HttpServletRequest request, Integer userId, Integer type, Integer hour, Integer recall, String reason) throws Exception {
        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser)session.getAttribute("adminUser");
        Integer adminUserId = adminUser.getId();

        User user = userMapper.selectById(userId);
        Map<String, String> pushData = new HashMap<>();
        pushData.put("type", "0");

        String desc = null;
        if(type == -1){     //解除封禁
            user.setStatus(0);

            //更新状态
            UserSealLog userSealLog = userSealLogMapper.selectNewestLog(userId);
            if(userSealLog != null && userSealLog.getStatus() == 0){
                userSealLog.setStatus(1);
                userSealLogMapper.updateById(userSealLog);
            }

            pushData.put("title", "解除封禁通知");
            pushData.put("content", "您的账号已经解除封禁状态，欢迎您的继续使用");

            desc = "解除"+userId+"禁用状态，理由："+reason;
        }else if(type == 0){    //永久封禁
            user.setStatus(1);

            //添加封禁记录
            UserSealLog userSealLog = new UserSealLog(userId, 0, reason, 0, adminUserId);
            userSealLogMapper.insert(userSealLog);

            pushData.put("title", "解除封禁通知");
            pushData.put("content", "您的账号已被永久封禁，具体原因为："+reason);

            desc = "永久封禁"+userId+"，理由："+reason;
        }else if(type == 1){    //临时封禁
            user.setStatus(1);

            //添加封禁记录
            UserSealLog userSealLog = new UserSealLog(userId, hour, reason, 0, adminUserId);
            userSealLogMapper.insert(userSealLog);

            pushData.put("title", "解除封禁通知");
            pushData.put("content", "您的账号因触犯"+reason+"，先系统决定将您的账号封禁"+hour+"小时，在此期间您的账号将不能使用，封禁结束后即可再次使用。");

            desc = "临时封禁"+userId+"用户"+hour+"小时，理由："+reason;
        }
        userMapper.updateById(user);

        //禁用，强制用户退出app
        if(user.getStatus() == 1){
            String key = "token:"+user.getToken();
            redisTemplate.expire(key, -1, TimeUnit.MINUTES);

            //撤回被封禁用户所有发送的消息
            if(recall == 1){
                List<UserImLog> userImLogs = userImLogMapper.selectByUserIdAndStatus(user.getId(), 0);
                for(UserImLog userImLog : userImLogs){
                    IMUtil.recall(userImLog.getMsgId(), Long.parseLong(userImLog.getMsgTimestamp()),
                            app.getIdPrefix()+userImLog.getFromUserId(), app.getIdPrefix()+userImLog.getToUserId(), app);

                    userImLog.setStatus(1);
                    userImLogMapper.updateById(userImLog);
                }
            }
        }

        //推送消息
        pushMessageService.pushGeneralMessage(userId, pushData);

        //记录操作日志
        operationService.addOperationLog(request, desc);

        return Result.returnSuccess(null);
    }

    @Override
    public Result updAudit(HttpServletRequest request, Integer userId, Integer audit) throws Exception {
        UserSet userSet = userSetMapper.selectByUserId(userId);

        UserSet set = new UserSet();
        set.setAudit(audit);
        if(userSet != null){
            if(userSet.getAudit().equals(audit)){
                if(audit.equals(0)){
                    return Result.returnFailure("可认证状态已处于开启状态，无需重复操作");
                }else{
                    return Result.returnFailure("可认证状态已处于关闭状态，无需重复操作");
                }
            }else{
                set.setId(userSet.getId());
                userSetMapper.updateById(set);
            }
        }else{
            set.setUserId(userId);
            userSetMapper.insert(set);
        }

        if(audit == 0){
            operationService.addOperationLog(request, userId+"开启可认证状态");
        }else{
            operationService.addOperationLog(request, userId+"关闭可认证状态");
        }

        return Result.returnSuccess(null);
    }

    @Override
    public Result disableImei(HttpServletRequest request, Integer userId, String imei, String reason) throws Exception {
        String desc;
        DisableImei disableImei = imeiMapper.getDisableImei(imei);
        if(StringUtil.isEmpty(reason)){ //启用设备
            if (disableImei != null) {
                imeiMapper.deleteById(disableImei.getId());
            }
            desc = "通过用户" + userId + "启用设备" + imei;
        }else{ //禁用设备
            if (disableImei == null) {
                disableImei = new DisableImei(userId, imei, reason);
                imeiMapper.insert(disableImei);

                //踢出登录状态
                List<User> users = userMapper.selectByImei(imei);
                for(User user : users){
                    String key = "token:"+user.getToken();
                    redisTemplate.expire(key, -1, TimeUnit.MINUTES);
                }
            }
            desc = "通过用户" + userId + "禁用设备" + imei + "，理由：" + reason;
        }

        operationService.addOperationLog(request, desc);

        return Result.returnSuccess(null);
    }

    @Override
    public Result toEditInvite(HttpServletRequest request, Integer userId) throws Exception {
        Map<String, Object> data = new HashMap<>();

        //获取用户的邀请者id
        Integer inviteId = userInviteLogMapper.getInviteIdByUserId(userId);
        data.put("inviteId", inviteId);

        return Result.returnSuccess(data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result editInvite(HttpServletRequest request, Integer editType, Integer userId, Integer type, Integer inviteId) throws Exception {
        String desc = "";
        if(editType == 1){  //编辑/添加邀请者
            User user = userMapper.selectById(inviteId);
            if(user == null){
                return Result.returnFailure("邀请者不存在");
            }

            Channel channel = channelMapper.selectByUserId(userId);
            if(channel != null && channel.getPid() == 0){
                return Result.returnFailure("顶级渠道商不能添加邀请者");
            }

            if(type == 0){
                Channel inviteChannel = channelMapper.selectByUserId(inviteId);
                if(inviteChannel != null){
                    return Result.returnFailure("邀请者为渠道商，不能添加为app分享邀请");
                }
            }else if(type == 1){
                channel = channelMapper.selectByUserId(inviteId);
                if(channel == null){
                    return Result.returnFailure("渠道用户不存在");
                }
            }

            //移除已有的邀请关系
            UserInviteLog userInviteLog = userInviteLogMapper.selectByUserId(userId);
            if(userInviteLog != null){
                userInviteLog.setStatus(1);
                userInviteLogMapper.updateById(userInviteLog);
            }
            ChannelUserLog channelUserLog = channelUserLogMapper.selectByUserId(userId);
            if(channelUserLog != null){
                channelUserLog.setStatus(1);
                channelUserLogMapper.updateById(channelUserLog);
            }

            if(type == 0){
                userInviteLog = new UserInviteLog();
                userInviteLog.setUserId(userId);
                userInviteLog.setInviteUserId(inviteId);
                userInviteLogMapper.insert(userInviteLog);
            }else if (type == 1){
                channelUserLog = new ChannelUserLog(channel.getId(), userId);
                channelUserLogMapper.insert(channelUserLog);
            }
            desc = "为"+userId+"用户编辑/添加邀请者"+inviteId;
        }else if(editType == 2){  //取消邀请者
            UserInviteLog userInviteLog = userInviteLogMapper.selectByUserId(userId);
            if(userInviteLog != null){
                userInviteLog.setStatus(1);
                userInviteLogMapper.updateById(userInviteLog);
            }
            ChannelUserLog channelUserLog = channelUserLogMapper.selectByUserId(userId);
            if(channelUserLog != null){
                channelUserLog.setStatus(1);
                channelUserLogMapper.updateById(channelUserLog);
            }
            desc = "成功取消"+userId+"的邀请者";
        }
        operationService.addOperationLog(request, desc);

        Map<String, Object> data = new HashMap<>();
        data.put("desc", desc);
        return Result.returnSuccess(data);
    }

    @Override
    @Transactional
    public Result recharge(HttpServletRequest request, Integer id, Integer type, Double number, String desc) throws Exception {
        Map<String, Object> data = new HashMap<>();

        User user = userMapper.selectById(id);
        if(user == null){
            return Result.returnFailure("用户不存在");
        }

        UserWallet wallet = userWalletMapper.getByUserId(id);
        if(wallet == null){
            wallet = new UserWallet(id, 0, 0, 0.0, 0.0);
        }

        if(type == 0){
            int num = number.intValue();
            wallet.setTotalCoin(wallet.getTotalCoin() + num);
            wallet.setActiveCoin(wallet.getActiveCoin() + num);

            UserCoinLog userCoinLog = new UserCoinLog(id, 0, 4, num, desc);
            userCoinLogMapper.insert(userCoinLog);

            operationService.addOperationLog(request, id+"用户金币充值，充值数量："+number);

        }else if(type == 1){
            wallet.setTotalCredit(wallet.getTotalCredit() + number);
            wallet.setActiveCredit(wallet.getActiveCredit() + number);

            UserCreditLog userCreditLog = new UserCreditLog(id, 0, 4, number, desc);
            userCreditLogMapper.insert(userCreditLog);

            operationService.addOperationLog(request, id+"用户积分充值，充值数量："+number);
        }

        if(wallet.getId() == null){
            userWalletMapper.insert(wallet);
        }else{
            userWalletMapper.updateById(wallet);
        }

        data.put("wallet", wallet);
        return Result.returnSuccess(data);
    }

    /**
     * 获取邀请用户明细
     * @Author Shane
     * @Date 2019/10/2813:21
     * @return
     **/
    @Override
    public Result inviteUserList(HttpServletRequest request, Integer inviteUserId, Integer userId,
                                 Integer type, String time, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(StringUtil.isEmpty(time) && inviteUserId == null && userId == null && type == null){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/invite/viewList")){
                data.put("inviteUserList", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = userInviteLogMapper.getInviteUserList(p, inviteUserId, userId, type, beginTime, endTime);
        List<Map<String, Object>> inviteUserList = iPage.getRecords();

        data.put("inviteUserList", inviteUserList);
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "获取邀请用户数据列表");

        return Result.returnSuccess(data);
    }

    @Override
    public Result changeGender(HttpServletRequest request, Integer id) throws Exception {
        User user = userMapper.selectById(id);
        user.setGender(user.getGender() == 0 ? 1 : 0);
        userMapper.updateById(user);

        //IM更新性别
        IMUtil.updateUinfo(app.getIdPrefix()+id, null, null, user.getGender(), app);

        operationService.addOperationLog(request, "变更"+id+"用户性别");

        return Result.returnSuccess(null);
    }

    @Override
    public Result editRemark(HttpServletRequest request, Integer id, String remark) throws Exception {
        User user = userMapper.selectById(id);
//        user.setRemark(remark);
        userMapper.updateById(user);

        operationService.addOperationLog(request, "编辑"+id+"用户备注");

        return Result.returnSuccess(null);
    }

    @Override
    public Result updateCall(HttpServletRequest request, Integer id, Integer call) throws Exception {
        User user = userMapper.selectById(id);
//        user.setCall(call);
        userMapper.updateById(user);

        /*Boolean mute = false;
        if(call == 1){
            mute = true;
        }
        IMUtil.muteAv(host.getUserId(), mute, app);*/

        if(call != null){
            operationService.addOperationLog(request, user.getId() + "更新通话权限");
        }

        return Result.returnSuccess(null);
    }

    @Override
    public Result updateIM(HttpServletRequest request, Integer id, Integer im) throws Exception {
        User user = userMapper.selectById(id);
//        user.setIm(im);
        userMapper.updateById(user);

        if(im != null){
            operationService.addOperationLog(request, user.getId() + "更新IM权限");
        }

        return Result.returnSuccess(null);
    }

    @Override
    public Result updateIPA(HttpServletRequest request, Integer userId, Integer invitePeopleAward) throws Exception {
        User user = userMapper.selectById(userId);
        /*if(user.getInvitePeopleAward().equals(invitePeopleAward)){
            if(invitePeopleAward.equals(0)){
                return Result.returnFailure("人头奖已处于开启状态，无需重复操作");
            }else{
                return Result.returnFailure("人头奖已处于关闭状态，无需重复操作");
            }
        }else{
            user.setInvitePeopleAward(invitePeopleAward);
            userMapper.updateById(user);

            if(invitePeopleAward == 0){
                operationService.addOperationLog(request, userId+"开启人头奖");
            }else{
                operationService.addOperationLog(request, userId+"关闭人头奖");
            }
        }*/
        return Result.returnSuccess(null);
    }

    /**
     * 获取用户邀请充值数据列表
     * @Author AppiJ
     * @Date 2020/7/8 16:04
     * @param
     * @return
     */
    @Override
    public Result inviteRechargeList(HttpServletRequest request, Integer inviteUserId, String time, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(StringUtil.isEmpty(inviteUserId) && StringUtil.isEmpty(time)){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/dataStatis/inviteRecharge/viewList")){
                data.put("inviteRechargeList", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }
        String nowDate = DateUtil.getCurrTimeStr("yyyy-MM-dd");

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = userInviteLogMapper.getInviteRechargeList(p, inviteUserId, nowDate, beginTime, endTime);
        List<Map<String, Object>> inviteUserList = iPage.getRecords();

        data.put("inviteRechargeList", inviteUserList);
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "获取用户邀请充值数据列表");

        return Result.returnSuccess(data);
    }

    @Override
    public Result sendMsg(HttpServletRequest request, Integer userId, String msg) throws Exception {
        //客服id
        Integer customer_account = Integer.parseInt(sysConfigMapper.getValue("customer_account"));

        IMUtil.sendMsg(app.getIdPrefix()+customer_account, app.getIdPrefix()+userId, msg, app);

        return Result.returnSuccess(null);
    }

    @Override
    public Result toUserInfo(HttpServletRequest request, Integer id) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Map<String, Object> user = userMapper.toUserInfo(id);
        data.put("user", user);

        return Result.returnSuccess(data);
    }

    @Override
    public Result toEditImLimit(HttpServletRequest request, Integer userId) throws Exception {
        Map<String, Object> data = new HashMap<>();

        List<UserImLimitLog> userImLimitLogs = userImLimitLogMapper.selectByUserId(userId);
        for(UserImLimitLog userImLimitLog : userImLimitLogs){
            data.put(userImLimitLog.getType(), userImLimitLog);
        }

        return Result.returnSuccess(data);
    }

    @Override
    public Result editImLimit(HttpServletRequest request, Integer userId, String type, Integer num, String time) throws Exception {
        String desc;

        if(num == null){    //取消限制
            userImLimitLogMapper.deleteByType(userId, type);

            desc = "取消用户"+userId+"的"+type+"消息发送限制";
        }else{
            UserImLimitLog userImLimitLog = userImLimitLogMapper.selectByType(userId, type);

            Date beginTime = null, endTime = null;
            if(!StringUtil.isEmpty(time)){
                String[] arr = time.split(" - ");
                beginTime = DateUtil.parse(arr[0]);
                endTime = DateUtil.parse(arr[1]);
            }

            if(userImLimitLog == null){
                userImLimitLog = new UserImLimitLog(userId, type, num, beginTime, endTime);
                userImLimitLogMapper.insert(userImLimitLog);

                desc = "新增用户"+userId+"的"+type+"消息限制，限制频率："+num+"，限制时间："+time;
            }else {
                userImLimitLog.setNum(num);
                userImLimitLog.setBeginTime(beginTime);
                userImLimitLog.setEndTime(endTime);
                userImLimitLogMapper.updateById(userImLimitLog);

                desc = "更新用户"+userId+"的"+type+"消息限制，限制频率："+num+"，限制时间："+time;
            }
        }

        operationService.addOperationLog(request, desc);

        return Result.returnSuccess(null);
    }

    @Override
    public Result toEditPayConfig(HttpServletRequest request, Integer userId) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Map<String, Object> pay = payChannelConfigMapper.selectByUserPay(userId);
        data.put("pay", pay);
        return Result.returnSuccess(data);
    }

    @Override
    public Result editPayConfig(HttpServletRequest request, Integer userId, Integer payWay, Integer type) throws Exception {
        PayChannelConfig payChannelConfig = null;
        if(type == 0){
            payChannelConfig = payChannelConfigMapper.selectOne(payWay, type);
        }else{
            payChannelConfig = payChannelConfigMapper.selectOneNot(payWay, 0);
        }

        String payWayName = "";
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", userId);
        if(payWay == 1){
            wrapper.set("ali_pay", payChannelConfig.getId());
            payWayName = "支付宝";
        }else if(payWay == 2){
            wrapper.set("wx_pay", payChannelConfig.getId());
            payWayName = "微信";
        }
        userMapper.update(null, wrapper);

        String desc = "更新用户"+payWayName+"支付渠道，变更后的渠道id为："+payChannelConfig.getId();
        operationService.addOperationLog(request, desc);

        return Result.returnSuccess(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result setClean(HttpServletRequest request, Integer userId, Integer clean, String reason) throws Exception {
        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser) session.getAttribute("adminUser");

        if(clean == 1){ //申请清退
            //更新用户状态
            User user = new User();
            user.setId(userId);
            user.setOnline(0);
            user.setStatus(1);
            userMapper.updateById(user);

            //更新清退状态
            UserSet userSet = new UserSet();
            userSet.setUserId(userId);
            userSet.setClean(clean);
            updateEntityService.updateUserSet(userSet);

            //添加禁用记录
            UserSealLog userSealLog = new UserSealLog(userId, 0, reason, 0, adminUser.getId());
            userSealLogMapper.insert(userSealLog);

            //删除token
            user = userMapper.selectById(userId);
            String key = ConstantsUtil.USER_TOKEN + user.getToken();
            redisTemplate.expire(key, -1, TimeUnit.MINUTES);

            //删除在线
            key = ConstantsUtil.USER_ONLINE + userId;
            if(redisTemplate.hasKey(key)){
                redisTemplate.expire(key, -1, TimeUnit.MINUTES);

                //记录下线时间
                UserOnlineLog userOnlineLog = userOnlineLogMapper.selectNewestLog(userId);
                userOnlineLog.setDownTime(new Date());
                userOnlineLogMapper.updateById(userOnlineLog);
            }

        }

        return Result.returnSuccess(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result submitCleanWithdraw(HttpServletRequest request, Integer userId, String alipayName, String alipayNo, Double credit, Double amount) throws Exception{
        UserWallet userWallet = userWalletMapper.getByUserId(userId);
        if(!userWallet.getActiveCredit().equals(credit)){
            return Result.returnFailure("申请提现积分有误");
        }

        Integer money_to_credit_rate = Integer.parseInt(sysConfigMapper.getValue("money_to_credit_rate"));
        if(amount > credit/money_to_credit_rate){
            return Result.returnFailure("申请提现金额有误");
        }

        //更新清退状态
        UserSet userSet = new UserSet();
        userSet.setUserId(userId);
        userSet.setClean(2);
        updateEntityService.updateUserSet(userSet);

        //添加提现记录
        String orderNumber = StringUtil.getOrderNumber();
        UserWithdrawLog userWithdrawLog = new UserWithdrawLog(userId, 1, orderNumber, 1, alipayNo, alipayName, 0, credit, (int)(amount*100) , 0);
        userWithdrawLogMapper.insert(userWithdrawLog);

        //添加系统订单
        Integer payChannelConfigId = Integer.parseInt(sysConfigMapper.getValue("remit_alipay_config_id"));
        SysOrder sysOrder = new SysOrder(userId, orderNumber, 1, null, payChannelConfigId, userWithdrawLog.getAmount(), 0, 1, 0);
        sysOrderMapper.insert(sysOrder);

        //更新钱包
        String desc = "账户清退，" + userWithdrawLog.getCredit()+"积分提现"+(userWithdrawLog.getAmount()/100.0)+"元";
        yieldService.updateUserWallet(userId, userWithdrawLog.getId(), 12, -userWithdrawLog.getCredit(), desc, 1);

        return Result.returnSuccess(null);
    }
}
